// Nama			: Bagus Rahman Aryabima
// NIM			: 13509044
// Nama File	: Superblock.c
// Tanggal		: 3 Desember 2011
// Deskripsi	: Representasi Superblock pada 56FS

#include "Superblock.h"

// ********** Inisialisasi **********
void Initialize(Superblock *S) {
	
	(*S).Name = (char*) malloc (5*sizeof(char));
	(*S).Name = "Name";
	(*S).Size = 0;
	(*S).Status = '0';
}

// ********** Get & Set biasa **********

char *getName(Superblock S) {
	return (S.Name);
}

unsigned long getSize(Superblock S) {
	return (S.Size);
}

char getStatus(Superblock S) {
	return (S.Status);
}

void setName(Superblock *S, char *newName) {
	(*S).Name = newName;
}

void setSize(Superblock *S, unsigned long newSize) {
	(*S).Size = newSize;
}

void setStatus(Superblock *S) {
	char Current, newStatus;
	Current = getStatus(*S);
	
	switch (Current) {
		case '0':
			newStatus = '1';
			break;
		case '1':
			newStatus = '0';
			break;
		default:
			printf ("File System Unformatted");
			break;
	}
	
	(*S).Status = newStatus;
}

// ********** Get & Set ke hard drive **********

char *readName(FILE *Stream) {
	char *FSName;
	FSName = (char*) malloc (5*sizeof(char));
	
	fseek(Stream, 0, SEEK_SET);
	fgets(FSName, 5, Stream);
	
	return FSName;
}

unsigned long readSize(FILE *Stream) {
	char *FSSize;
	FSSize = (char*) malloc (5*sizeof(char));
	unsigned long Result;
	
	fseek(Stream, 4, SEEK_SET);
	fgets(FSSize, 5, Stream);
	
	Result = FSSize[0]*pow(2,24) + FSSize[1]*pow(2,16) + FSSize[2]*pow(2,8) + FSSize[3];
	return Result;
}

char readStatus(FILE *Stream) {
	char FSStatus;
	
	fseek(Stream, 8, SEEK_SET);
	FSStatus = fgetc(Stream);
	
	return FSStatus;
}

void writeName(FILE *Stream, char* newName) {
	fseek(Stream, 0, SEEK_SET);
	fputs(newName, Stream);
}

void writeSize(FILE *Stream, unsigned long newSize) {
	char C1, C2, C3, C4;
	C1 = newSize/(long)pow(2,24);
	C2 = (newSize%(long)pow(2,24))/(long)pow(2,16);
	C3 = (newSize%(long)pow(2,16))/(long)pow(2,8);
	C4 = newSize%(long)pow(2,28);
		
	fseek(Stream, 4, SEEK_SET);
	fputc(C1, Stream);
	fseek(Stream, 5, SEEK_SET);
	fputc(C2, Stream);
	fseek(Stream, 6, SEEK_SET);
	fputc(C3, Stream);
	fseek(Stream, 7, SEEK_SET);
	fputc(C4, Stream);
}

void writeStatus(FILE *Stream, char newStatus) {
	fseek(Stream, 8, SEEK_SET);
	fputc(newStatus, Stream);
}
